import jieba
from device.utils.redis_client import redis_client
from device.utils.stopwords import STOPWORDS


class DeviceStorage:
    """设备数据存储与索引维护（支持多字段模糊查询）"""
    # 支持模糊查询的字段
    SUPPORTED_FIELDS = ["name", "location"]
    DEVICE_KEY = 'device:info'

    # 存储当前设备的总条数，分页
    def _set_device_info(self,data):
        redis_client.hset(self.DEVICE_KEY,mapping=data)
        redis_client.expire(self.DEVICE_KEY,60)

    def _get_hash_key(self, device_id):
        """设备详情的Hash键：device:{id}:info"""
        return f"device:{device_id}:info"

    def _get_index_key(self, field, word):
        """字段分词索引键：device:index:{field}:{word}"""
        return f"device:index:{field}:{word}"

    def _filter_words(self, words):
        """过滤停用词和空字符串"""
        return [w for w in words if w.strip() and w not in STOPWORDS]

    def create_device(self, device_id, data,expire=60):
        """创建设备并建立索引"""
        try:
            # 1. 存储设备详情到Hash
            hash_key = self._get_hash_key(device_id)
            redis_client.hset(hash_key, mapping=data)
            redis_client.expire(hash_key, expire)
            # 2. 为支持的字段建立分词索引
            for field in self.SUPPORTED_FIELDS:
                value = data.get(field, "").strip().lower()
                if not value:
                    continue
                # 分词并过滤
                words = jieba.lcut(value)
                valid_words = self._filter_words(words)
                # 每个词对应一个Set，存储包含该词的设备ID
                for word in valid_words:
                    index_key = self._get_index_key(field, word)
                    redis_client.sadd(index_key, device_id)
                    redis_client.expire(index_key, expire)
            return True
        except Exception as e:
            print(f"创建设备失败：{e}")
            return False

    def get_device(self, device_id):
        """获取设备详情"""
        data = redis_client.hgetall(self._get_hash_key(device_id))
        return {k.decode(): v.decode() for k, v in data.items()} if data else None

    def delete_device(self):
        cursor = 0  # SCAN游标，初始为0
        count = 1000  # 每次扫描的样本量（可根据数据量调整）
        deleted_count = 0  # 统计删除的键数量

        while True:
            # 扫描所有以'device:'开头的键（使用SCAN避免阻塞）
            cursor, keys = redis_client.scan(
                cursor=cursor,
                match='device:*',
                count=count
            )

            if keys:
                # 批量删除这些键
                deleted = redis_client.delete(*keys)
                deleted_count += deleted
                print(f"已删除{deleted}个键，当前累计删除{deleted_count}个")

            # 游标为0时，遍历结束
            if cursor == 0:
                break
        print('删除成功')

    def get_device_all(self):
        """获取设备详情"""
        cursor, data = redis_client.scan(
            cursor=0,
            match="device:*:info",
            count=1000  # 每次迭代获取1000个键（可根据设备数量调整）
        )
        return {k.decode(): v.decode() for k, v in data.items()} if data else None